package com.example.testapp.activity.activity.read;

import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.testapp.R;
import com.example.testapp.activity.model.NewsBean;
import com.example.testapp.activity.view.ImageLoader;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by l on 2016/8/22.
 */
public class HttpViewActivity extends AppCompatActivity {

    private ListView mListView;
    private static String jsonURL = "http://www.imooc.com/api/teacher?type=4&num=30";//json数据网址

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_view);
        mListView = (ListView) findViewById(R.id.listview);
        new NewAsyncTask().execute(jsonURL);
    }

    /**
     * 构造一个AsyncTask，传入String类型的URL，返回一个NewsBean对象，每一个对象就是
     * listview中的每一行数据，包括一个icon,title,content
     */
    public class NewAsyncTask extends AsyncTask<String, Void, List<NewsBean>> {

        @Override
        protected List<NewsBean> doInBackground(String... params) {
            return getJsonData(params[0]);
        }

        @Override
        protected void onPostExecute(List<NewsBean> result) {
            super.onPostExecute(result);
            NewsAdapter adapter = new NewsAdapter(HttpViewActivity.this, mListView, result);
            mListView.setAdapter(adapter);
        }
    }

    /**
     * 将URL网址上的json数据转化为我们所需的newsbean对象
     *
     * @return
     */
    private List<NewsBean> getJsonData(String url) {
        List<NewsBean> newsBeanList = new ArrayList<NewsBean>();  //保存解析出来的所有的数据

        try {
            String jsonString = readStream(new URL(url).openStream());//和url.openConnection().getInputStream()一样
            NewsBean  newsBean;
            JSONObject jsonObject;
            String newsUrl = null;
            String newsTitle = null;
            String newsContent = null;
            jsonObject = new JSONObject(jsonString);
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            for(int i = 0; i < jsonArray.length(); i++){
                jsonObject = jsonArray.getJSONObject(i);
                newsUrl = jsonObject.getString("picSmall");//图片网址
                newsTitle = jsonObject.getString("name"); //title
                newsContent = jsonObject.getString("description");//content
                newsBean = new NewsBean(newsUrl, newsTitle, newsContent);
                newsBeanList.add(newsBean);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return newsBeanList;
    }

    /**
     * 解析网络返回的数据
     */
    private String readStream(InputStream is) {
        InputStreamReader isReader;
        String  result = "";
        String  line = "";

        try {
            isReader = new InputStreamReader(is, "utf-8"); //将字节流转化为字符流
            BufferedReader bufferedReader = new BufferedReader(isReader);//从字符输入流中读取文本，缓冲各个字符，从而实现字符、数组和行的高效读取
            while ((line = bufferedReader.readLine()) != null){
                result += line;
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    public static class NewsAdapter extends BaseAdapter implements AbsListView.OnScrollListener {

        private LayoutInflater mInflater;
        private List<NewsBean> mList;
        public static String URLS[];//设置一个数组，用来保存所有图片的URL
        private boolean mFirstIn; //判断是否是第一次启动程序
        private int mStart, mEnd;//listview屏幕可视范围内的第一条item和最后一个item
        private ImageLoader mImageLoader;

        public NewsAdapter(Context context, ListView listView, List<NewsBean>  data) {
            mInflater = LayoutInflater.from(context);
            this.mList = data;
            URLS = new String[data.size()];
            mImageLoader = new ImageLoader(listView);
            for(int i = 0; i < data.size(); i++){
                URLS[i] = data.get(i).getNewsIconUrl();//将data中的每一个URL赋值给数组
            }
            listView.setOnScrollListener(this);
            mFirstIn = true;
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
           ViewHolder holder = null;
            if(convertView == null){
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.view_item_http, parent, false);
                holder.ivIcon = (ImageView) convertView.findViewById(R.id.iv_icon);
                holder.tvTitle = (TextView)convertView.findViewById(R.id.tv_title);
                holder.tvContent = (TextView)convertView.findViewById(R.id.tv_content);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }

            String url = mList.get(position).getNewsIconUrl();
            holder.ivIcon.setTag(url);

            mImageLoader.showImages(holder.ivIcon, url);

            holder.tvTitle.setText(mList.get(position).getNewsTitle());
            holder.tvContent.setText(mList.get(position).getNewsContent());

            return convertView;
        }

        public class ViewHolder{
            public ImageView  ivIcon;
            public TextView  tvTitle, tvContent;
        }

         /*
	     * 当listview滑动状态变化时调用
	     */
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
           if(scrollState == SCROLL_STATE_IDLE){
               //加载可见项
               mImageLoader.loadImages(mStart, mEnd);
           }else{
               //停止加载任务
               mImageLoader.cancelAllTasks();
           }
        }

        /*
	     * 当listview滑动的时候调用
	     */
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            mStart = firstVisibleItem;
            mEnd = mStart + visibleItemCount;
            //只在第一次加载的时候调用
            if(mFirstIn && visibleItemCount > 0){
                mImageLoader.loadImages(mStart, mEnd);
                mFirstIn = false;
            }
        }
    }
}
